package com.koron.device.filter;

import com.alibaba.fastjson.JSON;
import com.koron.bean.system.org.OrgBean;
import com.koron.bean.system.org.dto.OrgDto;
import com.koron.bean.system.post.query.PostUserQuery;
import com.koron.bean.system.post.vo.PostUserVo;
import com.koron.bean.workflow.SubmitterParam;
import com.koron.bean.workflow.WorkflowUser;
import com.koron.common.core.business.system.feign.SystemFeignService;
import com.koron.common.core.util.CommonUtils;
import com.koron.device.bean.EquipmentChangeVO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author twcao
 * @title: DeviceFilter
 * @projectName GDH_EAM_V2
 * @description: TODO
 * @date 2022/1/1917:27
 */
@Component
public class DeviceFilter {

    @Autowired
    private SystemFeignService systemFeignService;

    /**
     * 编制 配置 设备管理单位负责人审批审批人
     * @param factory
     * @param submitterParam
     * @return
     */
    @TaskAnnotation("task0Submitter")
    public List<WorkflowUser> task0Submitter(SessionFactory factory, SubmitterParam submitterParam) {
        EquipmentChangeVO equipmentChange = JSON.parseObject(submitterParam.getFormVariables(), EquipmentChangeVO.class);
        // 设备管理单位
        String mangerOrgs = equipmentChange.getEquipDeptId();
        // 岗位
        List<String> posts = postCode(submitterParam);
        List<String> orgs = orgs(submitterParam);
        if(CollectionUtils.size(orgs) == 1 && StringUtils.equals(orgs.get(0), mangerOrgs)) {
            List<WorkflowUser> users = filter(factory, account(submitterParam), Arrays.asList(posts.get(1)), orgs);
            return CollectionUtils.isEmpty(users) ? new ArrayList<>() : users;
        }
        List<WorkflowUser> users = filter(factory, account(submitterParam), Arrays.asList(posts.get(0)), Arrays.asList(mangerOrgs));
        return CollectionUtils.isEmpty(users) ? new ArrayList<>() : users;
    }

    /**
     * 只发送给当前设备管理单位所在部门及下级单位的部门副总经理（机电）
     * @param factory
     * @param submitterParam
     * @return
     */
    @TaskAnnotation("task1Submitter")
    public List<WorkflowUser> task1Submitter(SessionFactory factory, SubmitterParam submitterParam) {
        EquipmentChangeVO equipmentChange = JSON.parseObject(submitterParam.getFormVariables(), EquipmentChangeVO.class);
        // 设备管理单位
        String mangerOrgs = equipmentChange.getEquipDeptId();
        // 所在部门id
        List<String> deptIds = getDeptIdByOrgId(Arrays.asList(mangerOrgs));
        PostUserQuery query = new PostUserQuery();
        query.setParentOrgIdList(deptIds);
        query.setPostIdList(postCode(submitterParam));
        // 设备管理单位所在部门及其所有下级组织下的人员，根据岗位查询
        List<PostUserVo> vos = CommonUtils.ok(systemFeignService.queryPostList(query));
        if(CollectionUtils.isEmpty(vos)) {
            return new ArrayList<>();
        }
        List<WorkflowUser> users = new ArrayList<>();
        vos.stream().forEach(vo -> {
            WorkflowUser user = new WorkflowUser();
            user.setCode(vo.getUserAccount());
            user.setName(vo.getUserName());
            users.add(user);
        });
        return users;
    }

    /**
     * 只发送给当前设备管理单位所在部门的部门总经理
     * @param factory
     * @param submitterParam
     * @return
     */
    @TaskAnnotation("task2Submitter")
    public List<WorkflowUser> task2Submitter(SessionFactory factory, SubmitterParam submitterParam) {
        // 设备异动表单
        EquipmentChangeVO equipmentChange = JSON.parseObject(submitterParam.getFormVariables(), EquipmentChangeVO.class);
        String mangerOrgs = equipmentChange.getEquipDeptId();
        // 设备管理单位所属部门
        List<String> deptIds = getDeptIdByOrgId(Arrays.asList(mangerOrgs));
        List<WorkflowUser> users = filter(factory, account(submitterParam), postCode(submitterParam), deptIds);
        if(CollectionUtils.isEmpty(users)) {
            return new ArrayList<>();
        }
        return users;
    }

    /**
     * 自动发送至生产技术部的部门总经理
     * @param factory
     * @param submitterParam
     * @return
     */
    @TaskAnnotation("task4Submitter")
    public List<WorkflowUser> task4Submitter(SessionFactory factory, SubmitterParam submitterParam) {
        List<WorkflowUser> users = filter(factory, account(submitterParam), postCode(submitterParam), orgs(submitterParam));
        if(CollectionUtils.isEmpty(users)) {
            return new ArrayList<>();
        }
        return users;
    }

    /**
     * 手动选择人
     * @param factory
     * @param submitterParam
     * @return
     */
    @TaskAnnotation("task4Handler")
    public List<WorkflowUser> task4Handler(SessionFactory factory, SubmitterParam submitterParam) {
        List<WorkflowUser> users = filter(factory, account(submitterParam), postCode(submitterParam), orgs(submitterParam));
        return users;
    }


    /**
     * 获取岗位
     * @param submitterParam
     * @return
     */
    private List<String> postCode(SubmitterParam submitterParam) {
        List<WorkflowUser> users = submitterParam.getUsers();
        if(CollectionUtils.isEmpty(users)) {
            return new ArrayList<>();
        }
        // 岗位编码
        List<String> postCodes = users.stream().filter(row -> row.getType() == 2).map(WorkflowUser::getCode).collect(Collectors.toList());
        return postCodes;
    }

    /**
     * 人员
     * @param submitterParam
     * @return
     */
    private List<String> account(SubmitterParam submitterParam) {
        List<WorkflowUser> users = submitterParam.getUsers();
        if(CollectionUtils.isEmpty(users)) {
            return new ArrayList<>();
        }
        // 人员账号
        List<String> userAccounts = users.stream().filter(row -> row.getType() == 0).map(WorkflowUser::getCode).collect(Collectors.toList());
        return userAccounts;
    }

    /**
     * 组织
     * @param submitterParam
     * @return
     */
    private List<String> orgs(SubmitterParam submitterParam) {
        List<WorkflowUser> users = submitterParam.getUsers();
        if(CollectionUtils.isEmpty(users)) {
            return new ArrayList<>();
        }
        // 人员组织
        List<String> orgs = users.stream().filter(row -> row.getType() == 1).map(WorkflowUser::getCode).collect(Collectors.toList());
        return orgs;
    }

    /**
     * 根据岗位和组织查询审批人
     * 人员列表 && 组织列表 && 岗位列表
     * @param factory 会话
     * @param accounts 人员列表
     * @param orgList 组织列表
     * @param postCodes 岗位列表
     * @return
     */
    private List<WorkflowUser> filter(SessionFactory factory, List<String> accounts, List<String> postCodes, List<String> orgList) {
        if(CollectionUtils.isEmpty(postCodes) && CollectionUtils.isEmpty(orgList)) {
            return null;
        }
        PostUserQuery query = new PostUserQuery();
        query.setPostIdList(postCodes);
        query.setOrgIdList(orgList);
        List<PostUserVo> vos = CommonUtils.ok(systemFeignService.queryPostList(query));
        List<WorkflowUser> users = new ArrayList<>();
        vos.stream().forEach(vo -> {
            WorkflowUser user = new WorkflowUser();
            if(!CollectionUtils.isEmpty(accounts) && !accounts.contains(user.getCode())) {
                return;
            }
            user.setCode(vo.getUserAccount());
            user.setName(vo.getUserName());
            users.add(user);
        });
        if (users.size() == 0) {
            return null;
        }
        return users;
    }

    private List<String> getDeptIdByOrgId(List<String> orgIds) {
        OrgDto orgDto = new OrgDto();
        orgDto.setOrgIds(orgIds);
        List<OrgBean> depts = CommonUtils.ok(systemFeignService.queryDeptByOrgIdList(orgDto));
        return depts.stream().map(OrgBean::getDeptId).collect(Collectors.toList());
    }
}
